package com.cx.controller.lq;

import com.cx.constant.ConstantData;
import com.cx.pojo.ResultData;
import com.cx.pojo.User;
import com.cx.service.lq.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;


@Controller
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;


    @RequestMapping("login")
    @ResponseBody
    public ResultData login(HttpSession session, String userName,String pwd) {
        User user = userService.selectByUserNameAndPwd(userName, pwd);
        ResultData resultData =new ResultData();
        if (user!=null) {
            resultData.setCode(0);
            resultData.setMessage("登录成功");
            resultData.setData(user);
            session.setAttribute(ConstantData.SESSION_KEY,user);

        } else {
            resultData.setCode(1);
            resultData.setMessage("用户名或密码错误");
            resultData.setData(null);
        }
        return resultData;
    }

    @RequestMapping("getuser")
    @ResponseBody
    public User getUser(HttpSession session){
        User user = (User) session.getAttribute(ConstantData.SESSION_KEY);
        return user;
    }
    @RequestMapping("getpassword")
    @ResponseBody
    public String getUserpassword(HttpSession session) {
        User user = (User) session.getAttribute(ConstantData.SESSION_KEY);
        int userId = user.getUserId();
        String password = userService.findByUserId(userId);
        System.out.println(userId);
        return password;
    }
    @RequestMapping("changepwd")
    @ResponseBody
    public String changepwd(HttpSession session,String newpassword){
        User user = (User) session.getAttribute(ConstantData.SESSION_KEY);
        int userId = user.getUserId();
        int affect = userService.changePassword(userId,newpassword);
        if (affect>0)
            return "success";
        else
            return "fail";
    }



}